package com.nuanshui.heatedloan.module.features;

import com.alibaba.dubbo.config.annotation.Reference;
import com.nuanshui.framework.lang.ClassUtil;
import com.nuanshui.framework.lang.SysStringUtils;
import com.nuanshui.framework.res.ResourceFacade;
import com.nuanshui.framework.springContext.SpringContextUtil;
import com.nuanshui.framework.utils.LogUtil;
import com.nuanshui.heatedloan.baseservice.facade.ImageService;
import com.nuanshui.heatedloan.baseservice.service.CommonServiceImpl;
import com.nuanshui.heatedloan.constant.GlobalParam;
import com.nuanshui.heatedloan.constant.TransactionManagerType;
import com.nuanshui.heatedloan.model.Image;
import com.nuanshui.heatedloan.module.model.FeatureAttribute;
import com.nuanshui.heatedloan.module.model.FeatureForm;
import com.nuanshui.heatedloan.module.model.FeatureItem;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;


@Service
@Transactional(readOnly = true,value=TransactionManagerType.MODULE_TRANSACTION_MANAGER)
public class FeatureManager extends CommonServiceImpl implements IFeatureManager {

	private static final Logger logger = LoggerFactory.getLogger(FeatureManager.class);
	
	class FeatureAttributeType{
		private String moduleName;
		private Class<?> clazz;

		public String getModuleName() {
			return moduleName;
		}

		public void setModuleName(String moduleName) {
			this.moduleName = moduleName;
		}

		public Class<?> getClazz() {
			return clazz;
		}

		public void setClazz(Class<?> clazz) {
			this.clazz = clazz;
		}
		
	}
	
	Map<Integer, List<FeatureAttributeType>> maps;
	
	@Autowired
	protected ResourceFacade resourceFacade;

	@Reference(url = GlobalParam.BASESERVICE_DUBBO_SERVER, timeout = GlobalParam.DUBBO_SERVER_TIME_OUT,version = GlobalParam.BASESERVICE_DUBBO_SERVER_VERSION)
	private ImageService imageService;
	
	public FeatureManager() {
		
	}
	
	private void initialize()
	{
		if(maps==null || maps.isEmpty()){
			maps = new HashMap<Integer, List<FeatureAttributeType>>();
			loadFeatures();
		}
	}
	
	private void loadFeatures() {
		Set<Class<?>> classFeatures = ClassUtil.getAnnotationClasses(FeatureAttribute.class, "com.nuanshui.heatedloan.module.features");

		for (Class<?> clas : classFeatures) {
			addFeature(clas);
		}
	}

	private void addFeature(Class<?> clas) {
		FeatureAttribute item = clas.getAnnotation(FeatureAttribute.class);
		if (item != null) {
			List<FeatureAttributeType> list = maps.get(item.moduleId());
			
			if(list == null || list.isEmpty()){
				list = new ArrayList<FeatureAttributeType>();
				
				FeatureAttributeType type = new FeatureAttributeType();
				type.setModuleName(item.moduleName());
				type.setClazz(clas);
				
				list.add(type);
				maps.put(item.moduleId(), list);
				
			}else{
				
				FeatureAttributeType type = new FeatureAttributeType();
				type.setModuleName(item.moduleName());
				type.setClazz(clas);
				
				list.add(type);
			}
			
		}
	}
	
	
	@Override
	public void handleFeature(FeatureForm item)
	{
		item.getItem().setData(item.getItem().getInternalData());
		IModuleFeature featureItem=getFeature(item.getItem().getModuleId(),item.getItem().getModuleName()); // 这里，moduleName就用从前端带过的name和moduleName
		if(featureItem!=null)
		{
			featureItem.handleFeature(item);//这个是执行将数据不在featureItem的数据put到data里面的
		}
		
		afterHandleFeature(item);//这个是执行将featureItem的数据进行解析
	}
	
	
	private void afterHandleFeature(FeatureForm form)
	{
		List<FeatureItem> items = form.getItem().getInternalData();
		if(items == null) return ;
		for (int i = 0; i < items.size(); i++) {
			afterHandleFeatureItem(items.get(i));
		}
		form.getItem().setInternalData(null);
	}
	
	private void afterHandleFeatureItem(FeatureItem item) {
		//查找image
		if(SysStringUtils.isNotEmpty((item.getImageId())))
		{
			Image image = imageService.load(item.getImageId());
			if (image!= null && image.getKey() != null) {
				item.setImage(image);
			}
		}
		item.setServerData(null);
	}
	
	
	@Override
	@SuppressWarnings({ "rawtypes", "unchecked" })
	public IModuleFeature getFeature(int moduleId,String moduleName)
	{
		initialize();
		List<FeatureAttributeType> cls = this.maps.get(moduleId);
		IModuleFeature currentItem=null;
		if(cls!=null && !cls.isEmpty()){
			FeatureAttributeType item = null;
				for(FeatureAttributeType type : cls){
					if(StringUtils.isNotEmpty(type.getModuleName())){//如果当前循环的是一个默认的处理类，那么就先放到item里面
						if(type.getModuleName().equals(moduleName)){//如果不是，则判断是否是当前想要的那个处理类
							item = type;
							LogUtil.info(logger, "moduleId:"+moduleId+"对应的 moduleName: "+moduleName+"使用 <对应> 的的处理类<--"+type.getClazz().getSimpleName()+"--> 执行builder处理");
							break;
						}
					}else{
						LogUtil.info(logger, "moduleId:"+moduleId+"对应的moduleName: "+ (moduleName == null ? "为空": moduleName)+ "使用 <默认> 的处理类<--"+type.getClazz().getSimpleName()+"--> 执行builder处理");
						item = type;//这里=只会有一个默认的处理类
					}
				}
			
				Class clas = item.getClazz();
				currentItem = (IModuleFeature)SpringContextUtil.getBean(clas);
			}
			
		return currentItem;
	}
	
}
